/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package da;

import da.exceptions.NonexistentEntityException;
import da.exceptions.PreexistingEntityException;
import da.exceptions.RollbackFailureException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entities.Complain;
import entities.Account;
import entities.Reply;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;

/**
 *
 * @author THOHCGC00177
 */
public class ReplyJpaController implements Serializable {

    public ReplyJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Reply reply) throws PreexistingEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Complain complainId = reply.getComplainId();
            if (complainId != null) {
                complainId = em.getReference(complainId.getClass(), complainId.getId());
                reply.setComplainId(complainId);
            }
            Account technicalId = reply.getTechnicalId();
            if (technicalId != null) {
                technicalId = em.getReference(technicalId.getClass(), technicalId.getId());
                reply.setTechnicalId(technicalId);
            }
            em.persist(reply);
            if (complainId != null) {
                complainId.getReplyList().add(reply);
                complainId = em.merge(complainId);
            }
            if (technicalId != null) {
                technicalId.getReplyList().add(reply);
                technicalId = em.merge(technicalId);
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findReply(reply.getId()) != null) {
                throw new PreexistingEntityException("Reply " + reply + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Reply reply) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Reply persistentReply = em.find(Reply.class, reply.getId());
            Complain complainIdOld = persistentReply.getComplainId();
            Complain complainIdNew = reply.getComplainId();
            Account technicalIdOld = persistentReply.getTechnicalId();
            Account technicalIdNew = reply.getTechnicalId();
            if (complainIdNew != null) {
                complainIdNew = em.getReference(complainIdNew.getClass(), complainIdNew.getId());
                reply.setComplainId(complainIdNew);
            }
            if (technicalIdNew != null) {
                technicalIdNew = em.getReference(technicalIdNew.getClass(), technicalIdNew.getId());
                reply.setTechnicalId(technicalIdNew);
            }
            reply = em.merge(reply);
            if (complainIdOld != null && !complainIdOld.equals(complainIdNew)) {
                complainIdOld.getReplyList().remove(reply);
                complainIdOld = em.merge(complainIdOld);
            }
            if (complainIdNew != null && !complainIdNew.equals(complainIdOld)) {
                complainIdNew.getReplyList().add(reply);
                complainIdNew = em.merge(complainIdNew);
            }
            if (technicalIdOld != null && !technicalIdOld.equals(technicalIdNew)) {
                technicalIdOld.getReplyList().remove(reply);
                technicalIdOld = em.merge(technicalIdOld);
            }
            if (technicalIdNew != null && !technicalIdNew.equals(technicalIdOld)) {
                technicalIdNew.getReplyList().add(reply);
                technicalIdNew = em.merge(technicalIdNew);
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = reply.getId();
                if (findReply(id) == null) {
                    throw new NonexistentEntityException("The reply with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Reply reply;
            try {
                reply = em.getReference(Reply.class, id);
                reply.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The reply with id " + id + " no longer exists.", enfe);
            }
            Complain complainId = reply.getComplainId();
            if (complainId != null) {
                complainId.getReplyList().remove(reply);
                complainId = em.merge(complainId);
            }
            Account technicalId = reply.getTechnicalId();
            if (technicalId != null) {
                technicalId.getReplyList().remove(reply);
                technicalId = em.merge(technicalId);
            }
            em.remove(reply);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Reply> findReplyEntities() {
        return findReplyEntities(true, -1, -1);
    }

    public List<Reply> findReplyEntities(int maxResults, int firstResult) {
        return findReplyEntities(false, maxResults, firstResult);
    }

    private List<Reply> findReplyEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Reply.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Reply findReply(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Reply.class, id);
        } finally {
            em.close();
        }
    }

    public int getReplyCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Reply> rt = cq.from(Reply.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
